import React, {Component} from 'react'
import {withRouter} from 'react-router-dom'
import PropTypes from 'prop-types'
import {connect} from 'react-redux'
import {setUserInfoAction} from "@/store/action";
import {setIsLogin, setToken} from "@/common/auth";
import './index.scss'
import Avatar from "@/components/avatar";

class Index extends Component {
  static propTypes = {
    userInfo: PropTypes.object.isRequired,
    setUserInfo: PropTypes.func.isRequired
  }
  state = {
    username: '',
    password: '',
    isDisabled: false
  }

  // 设置文本框值
  setUserInfo(type, event) {
    this.setState({
      [type]: event.target.value
    }, () => {
      const {username, password} = this.state;
      this.setState({
        isDisabled: username && password
      })
    })
  }

  loginEvt = () => {
    const {username, password, isDisabled} = this.state;
    if (username && password && isDisabled) {
      const info = {
        userId: 0,
        username,
        password,
        avatar: username.substr(0, 3)
      }
      setIsLogin(1);
      setToken(1);
      // setUserInfo(info);
      this.props.setUserInfo(info);
      this.props.history.push('/home');
    }
  }

  render() {
    return (
      <section className="login-container">
        <Avatar className="user-avatar" size="big" avatar={this.props.userInfo.avatar}/>
        <p className="form-item">
          <span className="input-tip">用户名</span>
          <input type="text"
                 className="form-input name-input"
                 placeholder="输入用户名"
                 onChange={this.setUserInfo.bind(this, 'username')}
          />
        </p>
        <p className="form-item">
          <span className="input-tip">密码</span>
          <input type="password"
                 className="form-input pwd-input"
                 placeholder="输入密码"
                 onChange={this.setUserInfo.bind(this, 'password')}
          />
        </p>

        <div
          className={`login-btn ${this.state.isDisabled ? 'active' : ''}`}
          onClick={this.loginEvt}
        >
          登录
        </div>
      </section>
    );
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
    userInfo: state.userInfo
  }
}

const maDispatchToProps = (dispatch, ownProps) => {
  return {
    setUserInfo: userInfo => dispatch(setUserInfoAction(userInfo))
  }
}

export default withRouter(connect(mapStateToProps, maDispatchToProps)(Index))